import time

setGlobalDuration(-1)

beginPythonInst(1)
soundfont(duration=1)
endPythonInst()

proc = startCsound()

notes = '''67 69 71 74 72 72 76 74 74 79 78 79 74 71 67 69 71 72 74 76 74 72 71 69 71 67 66 67 \
	69 62 66 69 72 71 69 71 67 69 71 74 72 72 76 74 74 79 78 79 74 71 67 69 71 64 74 72 \
	71 69 67 62 67 66 67 71 74 79 74 71 67 71 74 79 62 64 66 69 67 69 72 71 72 69 66 62 66 \
	69 72 71 69 71 67 69 71 74 72 72 76 74 74 79 78 79 74 71 67 69 71 64 74 72 71 69 67 62 \
	67 66 67 71 69 71 74 72 72 76 74 74 79 78 79 74 71 67 69 71 72 74 76 74 72 71 69 71 67 \
	66 67 69 62 66 69 72 71 69 71 67 69 71 74 72 72 76 74 74 79 78 79 74 71 67 69 71 64 74 \
	72 71 69 67 62 67 66 67 62 64 66 69 67 69 72 71 72 69 66 62 66 69 72 71 69 71 67 69 71 \
	74 72 72 76 74 74 79 78 79 74 71 67 69 71 64 74 72 71 69 67 62 67 66 67'''
list = [int(n) for n in notes.split()]

time.sleep(2)

mrk = markov(3)
mrk.mkSetList(list)
mrk.mkStartPlayback()

avg1 = 0
avg2 = 0

def pit():
    dict = {'soundfont': {}}
    dict['soundfont']['midipitch'] = mrk.next()+avg1
    sendEvent(1, dict, proc)

mrk2 = markov(3)
mrk2.mkSetList(list)
mrk2.mkStartPlayback()

def pit2():
    dict = {'soundfont': {}}
    dict['soundfont']['midipitch'] = mrk2.next()+avg2
    sendEvent(1, dict, proc)

tempo = .125

ti1 = pattern(tempo, pit, [1,1,2])
ti2 = pattern(tempo, pit2, [2,1,1])
ti1.start()
ti2.start()

playButton = None
playing = False
def onPlay(state):
    global playing, ti1, ti2, playButton
    print playButton.GetValue()
    if playing:
        ti1.play(False)
        ti2.play(False)
        playing = False
        playButton.SetLabel('Play')
    else:
        ti1.play()
        ti2.play()
        playing = True
        playButton.SetLabel('Stop')

def handleSlider(val):
    global avg1
    avg1 = val

def handleSlider2(val):
    global avg2
    avg2 = val

def handleSlider3(val):
    global ti1, ti2, tempo
    tempo = val*0.001
    ti1.changeTime(tempo)
    ti2.changeTime(tempo)

frame = beginGUI(size=(260,300))
playButton = makeToggle(frame, label='Play', pos=(90,20), function=onPlay)
makeSlider(frame, mini=-24, maxi=24, pos=(50,50), function=handleSlider)
makeSlider(frame, mini=-24, maxi=24, pos=(50,120), function=handleSlider2)
makeSlider(frame, init=125, mini=0, maxi=500, pos=(50,190), function=handleSlider3)
endGUI(frame)

